<template>
  <div class="outer-container" v-loading="loading">
    <template v-if="!loading">
      <template v-if="userId">
        <div class="top-container">
          <BasicInfo style="flex: 1" tag="person_infom" :id="userId"></BasicInfo>
          <div style="width: 40%;flex-direction: column;display: flex; gap:10px">
            <div style="width: 100%;display: flex; gap: 20px; flex-direction: column;">
              <dv-border-box12>
                <div style="display: flex;gap:10px; padding: 20px;">
                  <div style="width: 30%;">
                    <dv-decoration-9 style="width:150px;height:150px;margin: 0 auto">
                      <div class="tech-text" style="font-size: 48px; font-family: 'LCD', sans-serif; color: white;">{{
                        overallScore }}
                      </div>
                    </dv-decoration-9>
                    <div style="">
                      <h2 style="text-align: center; color: white;">综合风险指数</h2>
                    </div>
                  </div>
                  <Radar :data="data" style="width: 40%;"></Radar>
                  <div style="width: 30%;">
                    <Gauge :data="overallScore / 100"></Gauge>
                  </div>
                </div>
              </dv-border-box12>
              <LabelBox :labels="Object.values(metaStore.userLabels).flatMap(l => l)"></LabelBox>
            </div>
          </div>
        </div>
        <div class="bottom-container">
          <ScenarioBox title="赌博违规" :highlights="['f_transactions_22_to_6_amout', 'f_transactions_22_to_6_count']"
            scenario="gambling_card" scoreKey="gambling_scores" :id="userId"
            :labels="['f_transactions_22_to_6_count_in_tendency', 'f_transactions_0_to_4\'_count_tendency', 'f_small_amount_high_frequency_ratio_tendency', 'f_large_transaction_count_tendency', 'f_transactions_6_to_12_count_tendency', 'f_transactions_6_to_12_amout_tendency', 'f_transactions_22_to_6_count_tendency', 'f_transactions_22_to_6_amout_tendency', 'f_transactions_high_loss_posssibility', 'f_transactions_high_win_posssibility', 'f_large_transactions_in_out_tendency']">
          </ScenarioBox>
          <ScenarioBox title="伪冒注册" :highlights="['card_trans_count_mon', 'card_trans_sum_mon']"
            scenario="card_weimao_label" scoreKey="weimao_score" :id="userId"
            :labels="['card_trans_mean_mon_abnormal', 'card_trans_sum_mon_abnormal', 'card_trans_std_mon_abnormal']">
          </ScenarioBox>
          <ScenarioBox title="异常转账" scenario="abnorm_trans_card" scoreKey="abnorm_trfer_score_max_history"
            :highlights="['transfer_money_out_mon', 'transfer_money_in_mon']" :id="userId">
          </ScenarioBox>
        </div>
      </template>
      <div v-else>
        <el-empty description="该用户近期无风险" />
      </div>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUpdated, reactive, ref } from 'vue'
import BasicInfo from '../../components/BasicInfo.vue'
import ScenarioBox from '@/components/ScenarioBox.vue'
import Radar from '@/components/Radar.vue'
import LabelBox from '@/components/LabelBox.vue'
import { usePortraitStore } from '@/stores/portrait';
import { nebulaExec } from '@/utils/request'
import { useRoute } from 'vue-router'
import { getLastSixMonths } from '@/utils/misc'
import { storeToRefs } from 'pinia';
import { useScoreStore } from '@/stores/score'
import { max, mean, min } from 'lodash'
import { useSchemaStore } from '@/stores/schema'
import { useMetaStore } from '@/stores/meta'
import sm3 from 'sm-crypto'
import { isEmpty } from 'lodash'
import Bullet from '@/components/Bullet.vue'
import Gauge from '@/components/Gauge.vue'

const route = useRoute()

const scoreStore = useScoreStore()
const store = usePortraitStore();
const metaStore = useMetaStore()

const loading = ref(true)

store.mobile = sm3.sm3(route.params.id)

const data = ref([])

const userId = ref(null)
const overallScore = ref(0)

function weightedScore(arr) {
  const max = Math.max(...arr);
  const hasAbove60 = arr.some(num => num > 60);

  const sum = arr.reduce((acc, num) => acc + num, 0);

  // 根据sum调整加权分数的计算逻辑，sum越大分数越高
  let result;
  if (hasAbove60) {
    const factor = sum / (arr.length * 100);
    // const threshold = max + max / 100 * (100 - max)
    result = max + (100 - max) * factor;
  } else {
    const factor = sum / (arr.length * 60);
    result = max + (60 - max) * factor;
  }

  return result;
}

scoreStore.$subscribe((mutation, state) => {
  data.value = Object.entries(state.userScores).map(([k, v]) => {
    return {
      name: k,
      // star: v.length ? mean(v) * 100 : 0
      star: min([max(v) * 100 || 0, 100])
    }
  })
  console.log(mean([1]))
  // overallScore.value = Math.floor(mean(Object.values(state.userScores).map(v => mean(v))) * 100)
  // overallScore.value = Math.floor(weightedScore(Object.values(state.userScores).flatMap(v => (v)).map(v => v * 100)))
  // overallScore.value = Math.floor(weightedScore(Object.values(state.userScores).map(v => mean(v)).filter(v => !Number.isNaN(v)).map(v => v * 100)))
  overallScore.value = Math.floor(max(data.value.map(v => v.star)))
  console.log(Object.values(state.userScores).flatMap(v => (v)))
})

const fetchData = async function () {
  await useSchemaStore().load()

  const queryId = route.params.id.trim()
  if (queryId.length == 11) {
    const mobile = sm3.sm3(queryId).toUpperCase()
    console.log(mobile)
    const resp = await nebulaExec(`MATCH (m)-[e:mobile_belongsto]->(u) where id(m) == "${mobile}" return id(u)`)
    if (!isEmpty(resp)) {
      userId.value = resp['id(u)'][0]
    }
  } else if (queryId.length <= 19) {
    const cardId = sm3.sm3(queryId).toUpperCase()
    console.log(cardId)
    const resp = await nebulaExec(`MATCH (u)-[e:has_card]->(c) where id(c) == "${cardId}" return id(u)`)
    if (!isEmpty(resp)) {
      userId.value = resp['id(u)'][0]
    }
  } else { // 64位加密卡号
    const resp = await nebulaExec(`MATCH (u)-[e:has_card]->(c) where id(c) == "${queryId}" return id(u)`)
    if (!isEmpty(resp)) {
      userId.value = resp['id(u)'][0]
    }
  }

  loading.value = false
}

fetchData()

</script>

<style scoped>
.outer-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 0 20px 20px 20px;
  height: 100%;
}

.top-container {
  flex: 0 1 20%;
  display: flex;
  flex-direction: row;
  gap: 20px;
}

.bottom-container {
  flex: 1;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  /* margin-bottom: 80px; */
}

.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 28px;
}

.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 12px;
}
</style>
